import random
import schedule
import os
import tkinter
import time
import pyHook
start = [5, 5] #开始的头
snake = [
    start
    ] #表示贪吃蛇的容器
mapWidth = 20
mapHeight = 20
food = []
direction = 'd'
game = True
def setFood():
    global food
    food = []
    foodT = [random.randint(0, mapWidth - 1), random.randint(0, mapHeight - 1)]
    if foodT in snake:
        setFood()
    else:
        food = foodT

def renderMap():
    global mapWidth
    global mapHeight
    os.system('clear')
    for w in range(0, mapWidth):
        for h in range(0, mapHeight):
            if [w, h] in snake:
                print('*', end = '')
            elif w == food[0] and h == food[1]:
                print('$', end = '')
            else:
                print(' ', end = '')
        print()


def autoMov():
    schedule.every().second.do(mov)
    while game:
        schedule.run_pending()
        time.sleep(1)
def getDirection(event):
    global direction
    direction = event.keysym
    print(direction)
def mov():
    global food
    head = []
    head.append(snake[0][0])
    head.append(snake[0][1])
    copySnake = []
    if direction == 'w':
        head[0] -= 1
    elif direction == 'a':
        head[1] -= 1
    elif direction == 's':
        head[0] += 1
    elif direction == 'd':
        head[1] += 1

    if head in snake:
        print('game over!')
        game = False
        return
    snake.insert(0, head)

    if head[0] == food[0] and head[1] == food[1]: #被吃
        setFood()

    else:
        snake.pop()
    renderMap()

def testWord():
    print('i am working')

if __name__ == '__main__':
    setFood()
    mov()
    win=tkinter.Tk()
    frame=tkinter.Frame(win,width=200,height=200) 
    frame.bind("<Key>",getDirection) #触发的函数
    frame.focus_set()  #必须获取焦点
    frame.pack()
    win.mainloop()
    autoMov()
    # renderMap()
    # getDirection()
